﻿                       using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ThridGroup.ERP.DTO.ProductionSystem.ShiftSchedulingManagement.Procurement;
using ThridGroup.ERP.DTO.WarehouseManagement;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace ThridGroup.ERP.WarehouseManagement
{
    /// <summary>
    /// 采购入库Services
    /// </summary>
    public class ProcurementServices: ApplicationService, IProcurementServices
    {
        /// <summary>
        /// 采购入库仓储
        /// </summary>
        private readonly IRepository<ProcurementModelS, int> _procurementServices;
        /// <summary>
        /// 物料入库仓储
        /// </summary>
        private readonly IRepository<MaterialReceiptLineModelS, int> _materialReceiptLineServices;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="procurementServices">采购入库仓储</param>
        /// <param name="_materialReceiptLineServices">物料入库仓储</param>
        public ProcurementServices(IRepository<ProcurementModelS, int> procurementServices, IRepository<MaterialReceiptLineModelS, int> materialReceiptLineServices)
        {
            _procurementServices = procurementServices;
            _materialReceiptLineServices = materialReceiptLineServices;
        }

        /// <summary>
        /// 添加采购入库
        /// </summary>
        /// <param name="dto">采购入库信息</param>
        /// <returns></returns>
        public async Task<int> CreateProcurement(ProcurementDto dto)
        {
            var entity = ObjectMapper.Map<ProcurementDto, ProcurementModelS>(dto);
            var result = await _procurementServices.InsertAsync(entity);
            return result == null ? 0 : 1;
        }

        /// <summary>
        /// 查询采购入库（分页/条件）
        /// </summary>
        /// <param name="dto">查询条件</param>
        /// <returns></returns>
        public async Task<ProcurementQueryResult> QueryProcurement(GetProcurementDto dto)
        {
            var procurementList = await _procurementServices.GetListAsync();
            
            // 入库单编号查询
            procurementList = procurementList.WhereIf(!string.IsNullOrEmpty(dto.LnboundCode), t => t.LnboundCode.Contains(dto.LnboundCode)).ToList();
            
            // 入库单名称查询
            procurementList = procurementList.WhereIf(!string.IsNullOrEmpty(dto.LnboundName), t => t.LnboundName.Contains(dto.LnboundName)).ToList();
            
            // 供应商查询
            procurementList = procurementList.WhereIf(!string.IsNullOrEmpty(dto.Vendor), t => t.Vendor.Contains(dto.Vendor)).ToList();
            
            // 采购入库单号查询
            procurementList = procurementList.WhereIf(!string.IsNullOrEmpty(dto.ProcurementNumber), t => t.ProcurementNumber.Contains(dto.ProcurementNumber)).ToList();
            
            // 入库日期查询
            procurementList = procurementList.WhereIf(dto.LnboundDate.HasValue, t => t.LnboundDate.HasValue && t.LnboundDate.Value.Date == dto.LnboundDate.Value.Date).ToList();

            // 获取总记录数
            var totalCount = procurementList.Count;
            
            // 分页处理
            var pagedList = procurementList.Skip((dto.page - 1) * dto.limit).Take(dto.limit).ToList();
            var mappedList = ObjectMapper.Map<List<ProcurementModelS>, List<ProcurementDto>>(pagedList);

            return new ProcurementQueryResult
            {
                Data = mappedList,
                TotalCount = totalCount
            };
        }

        /// <summary>
        /// 修改采购入库
        /// </summary>
        /// <param name="dto">采购入库信息</param>
        /// <returns></returns>
        public async Task<int> UpdateProcurement(ProcurementDto dto)
        {
            var entity = ObjectMapper.Map<ProcurementDto, ProcurementModelS>(dto);
            var result = await _procurementServices.UpdateAsync(entity);
            return result == null ? 0 : 1;
        }

        /// <summary>
        /// 批量删除采购入库
        /// </summary>
        /// <param name="ids">采购入库ID列表</param>
        /// <returns></returns>
        public async Task BatchDeleteProcurement(List<int> ids)
        {
            if (ids == null || !ids.Any())
                return;
            await _procurementServices.DeleteDirectAsync(t => ids.Contains(t.Id));
        }

        /// <summary>
        /// 根据ID获取采购入库信息
        /// </summary>
        /// <param name="id">采购入库ID</param>
        /// <returns></returns>
        public async Task<ProcurementDto> GetProcurementById(int id)
        {
            var entity = await _procurementServices.GetAsync(id);
            return ObjectMapper.Map<ProcurementModelS, ProcurementDto>(entity);
        }


        /// <summary>
        /// 根据ID获取采购入库信息修改入库状态
        /// </summary>
        /// <param name="id">采购入库ID</param>
        /// <returns></returns>
        public async Task<int> GetProcurementStatus(int id)
        {
            var entity = await _procurementServices.GetAsync(id);
            entity.DocumentStatus = 1;
            var result = await _procurementServices.UpdateAsync(entity);
            return result == null ? 0 : 1;
        }

        // ================== 物料入库增删改查 ==================
        /// <summary>
        /// 添加物料入库
        /// </summary>
        public async Task<int> CreateMaterialReceiptLine(MaterialReceiptLineDto dto)
        {
            var entity = ObjectMapper.Map<MaterialReceiptLineDto, MaterialReceiptLineModelS>(dto);
            var result = await _materialReceiptLineServices.InsertAsync(entity);
            return result == null ? 0 : 1;
        }

        /// <summary>
        /// 查询物料入库（分页/条件）
        /// </summary>
        public async Task<MaterialReceiptLineQueryResult> QueryMaterialReceiptLine(string lnboundCode, int page = 1, int limit = 10)
        {
            var list = await _materialReceiptLineServices.GetListAsync();
            if (!string.IsNullOrEmpty(lnboundCode))
                list = list.Where(t => t.LnboundCode.Contains(lnboundCode)).ToList();
            var totalCount = list.Count;
            var pagedList = list.Skip((page - 1) * limit).Take(limit).ToList();
            var mappedList = ObjectMapper.Map<List<MaterialReceiptLineModelS>, List<MaterialReceiptLineDto>>(pagedList);
            return new MaterialReceiptLineQueryResult
            {
                Data = mappedList,
                TotalCount = totalCount
            };
        }

        /// <summary>
        /// 修改物料入库
        /// </summary>
        public async Task<int> UpdateMaterialReceiptLine(MaterialReceiptLineDto dto)
        {
            var entity = ObjectMapper.Map<MaterialReceiptLineDto, MaterialReceiptLineModelS>(dto);
            var result = await _materialReceiptLineServices.UpdateAsync(entity);
            return result == null ? 0 : 1;
        }

        /// <summary>
        /// 批量删除物料入库
        /// </summary>
        public async Task BatchDeleteMaterialReceiptLine(List<int> ids)
        {
            if (ids == null || !ids.Any())
                return;
            await _materialReceiptLineServices.DeleteDirectAsync(t => ids.Contains(t.Id));
        }

        /// <summary>
        /// 根据ID获取物料入库信息
        /// </summary>
        public async Task<MaterialReceiptLineDto> GetMaterialReceiptLineById(int id)
        {
            var entity = await _materialReceiptLineServices.GetAsync(id);
            return ObjectMapper.Map<MaterialReceiptLineModelS, MaterialReceiptLineDto>(entity);
        }
    }
}
